package cn.tedu.luban.worker.main.repository;

import cn.tedu.luban.passport.protocol.jwt.UserPrinciple;
import cn.tedu.luban.passport.sdk.security.LubanSecurityContext;
import cn.tedu.luban.worker.main.converter.WorkerAreaConverter;
import cn.tedu.luban.worker.main.mapper.WorkerAreaMapper;
import cn.tedu.luban.worker.protocol.bo.WorkerAreaBO;
import cn.tedu.luban.worker.protocol.dos.WorkerAreaDO;
import cn.tedu.luban.worker.protocol.param.WorkerRegistAreaParam;
import cn.tedu.luban.worker.protocol.param.WorkerRegistParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class WorkerAreaRepository {

    @Autowired
    private WorkerAreaMapper workerAreaMapper;

    @Autowired
    private WorkerAreaConverter workerAreaConverter;

    @Autowired
    private RedisTemplate redisTemplate;

    private static final String WORKER_AREA_CACHE_PREFIX="luban:worker:area:";

    public void deleteByUserId(Long userId) {
        workerAreaMapper.deleteByUserId(userId);

        //删除缓存
        redisTemplate.delete(WORKER_AREA_CACHE_PREFIX+userId);

    }

    public void saveWorkerAreas(WorkerRegistParam workerRegistParam) {
        List<WorkerRegistAreaParam> workerRegistAreaParams = workerRegistParam.getWorkerRegistAreaParams();
        List<WorkerAreaDO> workerAreaDOS=workerAreaConverter.params2dos(workerRegistAreaParams,workerRegistParam.getUserId());
        workerAreaMapper.batchInsert(workerAreaDOS);
        //删除缓存
        redisTemplate.delete(WORKER_AREA_CACHE_PREFIX+workerRegistParam.getUserId());
    }


    public List<WorkerAreaBO> getAreasByUserId(Long userId) {
//        //1.持久层查询 doList
//        List<WorkerAreaDO> workerAreaDOS=workerAreaMapper.selectByUserId(userId);
//        return workerAreaConverter.dos2bos(workerAreaDOS);
        String areaKey = WORKER_AREA_CACHE_PREFIX + userId;
        ListOperations opsForList = redisTemplate.opsForList();
        List<WorkerAreaBO> workerAreaBOS=null;
        //判断缓存中是否有数据
        if (redisTemplate.hasKey(areaKey)){
            //缓存命中，从缓存中获取数据
            workerAreaBOS = opsForList.range(areaKey, 0, -1);
        }else {
            List<WorkerAreaDO> workerAreaDOS = workerAreaMapper.selectByUserId(userId);
            workerAreaBOS=workerAreaConverter.dos2bos(workerAreaDOS);
            //添加到缓存中
            opsForList.leftPushAll(areaKey,workerAreaBOS);
        }
        return workerAreaBOS;
    }
}
